import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store";

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  routes,
  scrollBehavior() {
    return {
      x: 0,
      y: 0,
    };
  }
});

// 白名单
const whitelist = ["Home", "Detail", "Register", "Search", "Login"];
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 开启进度条
  NProgress.start();

  const token = store.state.User.token;

  if (token) {
    // console.log(1);
    if (to.name === "Login") {
      next("/home");
    } else {
      const isnickName = !!store.state.User.userMessage.nickName;
      if (isnickName) {
        next();
      } else {
        try {

          await store.dispatch("User/get_userMessage");
          next();
        } catch (e) {

          store.commit("User/remove_token");
          next("/login");
        }
      }
    }
  } else {
    if (whitelist.includes(to.name)) {
      next();
    } else {
      next("/login");
    }
  }

});
router.afterEach(() => {
  NProgress.done();
});
export default router;